package com.idea.relax.boot.file;

import com.idea.relax.tool.core.*;
import lombok.Getter;

import java.io.*;
import java.util.List;

/**
 * @author: 沉香
 * @date: 2023/4/19
 * @description:
 */
@Getter
public class FileObjects {

	private final List<FileObject> fileObjects;

	private final String uploadDir;

	private static RelaxFileProperties fileProperties;

	private static RelaxFileProperties getFileProperties() {
		if (fileProperties == null) {
			fileProperties = SpringUtil.getBean(RelaxFileProperties.class);
		}
		return fileProperties;
	}

	public FileObjects(List<FileObject> fileObjects) {
		this.fileObjects = fileObjects;
		this.uploadDir = FileUtil.getDir(getFileProperties().getParentPath(), getFileProperties().getUploadPath(), null, null);
	}

	public void toZip(OutputStream out) {
		ZipUtils.fileObjectToZip(fileObjects, out);
	}

	public void toZip(String name) {
		OutputStream out = null;
		try {
			out = new FileOutputStream(uploadDir + name + StringPool.DOT + "zip");
			ZipUtils.fileObjectToZip(fileObjects, out);
		} catch (FileNotFoundException e) {
			throw ExceptionUtil.unchecked(e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void compress(String outputPath, double scale, boolean flag){
		for (FileObject fileObject : fileObjects) {
			fileObject.compress(outputPath, scale, flag);
		}
	}

	public long count() {
		return Func.isEmpty(fileObjects) ? 0 : fileObjects.size();
	}

}
